﻿using StackExchange.Redis;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsistentHashing
{
    /// <summary>
    /// 负责维护物理节点的通信，包括连接，关闭，获取数据等
    /// </summary>
    public class Node
    {
        ConnectionMultiplexer redis = null;
        IDatabase redisWriteDB = null;
        string nodeName = "";

        public string NodeName 
        { 
            get
            { 
                return nodeName; 
            } 
            set 
            { 
                nodeName = value; 
            }
        }
        
        public Node(string config)
        {
            redis = ConnectionMultiplexer.Connect(config);
            redisWriteDB = redis.GetDatabase();
        }
        
        public void StringSet(string key, string value)
        {
            //redisWriteDB.StringSet("nnn", "kou"); 
            redisWriteDB.StringSet(key, value);
        }

        public string StringGet(string key)
        {
            //string h121 = redisWriteDB.StringGet("121", CommandFlags.PreferReplica);
            //Console.WriteLine("key[121], Value:[" + h121 + "]");
            //string hnnn = redisWriteDB.StringGet("nnn", CommandFlags.PreferReplica);
            //Console.WriteLine("key[nnn], Value:[" + hnnn + "]");
            return redisWriteDB.StringGet(key, CommandFlags.PreferReplica);
        }

        public IServer GetMaster()
        {
            IServer server = null;
            foreach (var endpoint in redis.GetEndPoints())
            {
                server = redis.GetServer(endpoint);
                //获取主机master
                if (!server.IsReplica) break;
            }
            return server;
        }

        public IServer GetSlave()
        {
            IServer server = null;
            foreach (var endpoint in redis.GetEndPoints())
            {
                server = redis.GetServer(endpoint);
                //获取主机master
                if (server.IsReplica) break;
            }
            return server;
        }

        public void MasterServerInfo()
        {
            IServer server = null;
            foreach (var endpoint in redis.GetEndPoints())
            { 
                server = redis.GetServer(endpoint);
                //获取主机master
                if (!server.IsReplica) break;
            }

            var info1 = server.Info();

            Console.WriteLine("All sections");
            foreach (var group in info1)
            {
                Console.WriteLine(group.Key + ":{");
                foreach (var col in group)
                {
                    Console.WriteLine("-     [" + col.Key + "]: [" + col.Value + "]");
                }
                Console.WriteLine("}");
            }
        }
    }
}
